/**
 * create by young (young2f@outlook.com) on 2020/12/4
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const moment = require('moment');
const table = 'Vendor';
module.exports = class extends base {
  async findVendorMaterial(body) {
    const { ctx } = this;
    console.log('find vendor material', body);
    const { code, tenantCode } = body;
    const list = await ctx.app.dbs.find('ProcureOrder', { tenantCode, vendorCode: code });
    console.log('find vendor material list', list);
    const _result = [];
    _.map(list, item => {
      const { materials=[] } = item;
      _result.push(...materials);
    });
    const result = _.uniqBy(_result, 'code');

    return { status: 'ok', result };
  }

  //当前合同额、当前采购额、已支付（付款申请结单）、未支付（采购合同和付款申请结单的差额）、入库金额、入库数量、入库与合同的差额（金额、数量）、收票金额、合同与收票差额。
  async findDetail(body) {
    const { ctx, service } = this;
    console.log('find customer findCustomerDetail', body);
    const { code, tenantCode, createdTs, division } = body;
    const list = [];
    let _payAmount = 0,
      _amount = 0,
      _inboundAmount = 0,
      invoiceAmount = 0;
    const queryRece = division ? { tenantCode, _accountName: division, 'vendorCode': code } : {
      tenantCode,
      'vendorCode': code
    };
    if (createdTs) {
      queryRece['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const list0 = await ctx.app.dbs.find('Receipt', queryRece);

    _.map(list0, item => {
      const { paymentAmount } = item;
      item.createdTs = item.date;
      if (paymentAmount) {
        _payAmount += paymentAmount;
        list.push(item);
      }
    });

    const query1 = division ? { tenantCode, division, 'vendorCode': code } : {
      tenantCode,
      'vendorCode': code
    };
    if (createdTs) {
      query1['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const list1 = await ctx.app.dbs.find('ProcureOrder', query1);
    _.map(list1, item => {
      const { amount = 0 } = item;
      item.createdTs = item.date;
      _amount += amount;
    });

    const inboundLots = await ctx.app.dbs.find('StoreLot', query1);
    _.map(inboundLots, item => {
      const { price = 0, lotCount = 0 } = item;
      _inboundAmount += price * lotCount;
    });

    const query2 = division ? { tenantCode, division, 'vendorCode': code, invoice: '已收票' } : {
      tenantCode, 'vendorCode': code, invoice: '已收票'
    };
    if (createdTs) {
      query2['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const list2 = await ctx.app.dbs.find('ProcureOrder', query2);

    _.map(list2, item => {
      const { amount } = item;
      item.createdTs = item.date;
      if (amount) {
        invoiceAmount += amount;
      }
    });
    const result = [
      { title: '总合同金额', value: 10 },
      { title: '总采购数量', value: 0 },
      { title: '已支付金额', value: 0 },
      { title: '未支付金额', value: 0 },
      { title: '总入库数量', value: 0 },
      { title: '总入库金额', value: 0 },
      { title: '入库与合同金额差额', value: 0 },
      { title: '入库与合同的数量差额', value: 0 },
      { title: '收票金额', value: 0 },
      { title: '合同与收票差额', value: 0 },
    ];
    //当前合同额、当前采购额、已支付（付款申请结单）、未支付（采购合同和付款申请结单的差额）、入库金额、入库数量、入库与合同的差额（金额、数量）、收票金额、合同与收票差额。
    return { status: 'ok', result };
  }

  async storeAssess(body) {
    const { ctx, service } = this;
    console.log('vendor storeAssess', body);
    const { tenantCode } = body;
    delete body['tenantName'];
    delete body['tenantCode'];
    const schema = await service.globalService.getModel({ table });
    const query = { tenantCode };
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;

    const result = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    return { status: 'ok', result };
  }

  async findMany(body) {
    const { ctx, service } = this;
    console.log('find vendor many', body);
    const { tenantCode } = body;
    delete body['tenantName'];
    delete body['tenantCode'];
    const schema = await service.globalService.getModel({ table });
    const query = { tenantCode };
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;

    const result = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    return { status: 'ok', result };

  }

  async updateOne(body) {
    const { ctx } = this;
    const { tenantCode, code } = body;
    const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, body);
    return { status: 'ok', result };
    return 'ok';
  }

  async deleteOne(body) {
    const { ctx } = this;
    const { tenantCode, code } = body;
    const result = await ctx.app.dbs.deleteOne(table, { tenantCode, code }, body);
    return { status: 'ok', result };
    return 'ok';
  }
};
